Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:

  • [[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]]
  • You should return [1,2,3,6,9,8,7,4,5].

题目大意:给定一个m * n的矩阵,按顺时针方向排列

题目难度:Medium

import java.util.*;
/**
 * Created by gzdaijie on 16/5/25
 */
public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) return new ArrayList<Integer>();
        int m = matrix.length;
        int n = matrix[0].length;

        int[][] dirs = {{0, 1},{1, 0},{0, -1},{-1, 0}};
        int top = 0, left = 0 ,right = n - 1, bottom = m - 1;
        int k = m * n, dir = 0, x = 0, y = 0;

        List<Integer> result = new ArrayList<>();
        while (k-- > 0) {
            result.add(matrix[x][y]);
            if (dir == 0 && y >= right) {
                top++;
                dir = (dir + 1) % 4;
            } else if (dir == 1 && x >= bottom) {
                right--;
                dir = (dir + 1) % 4;
            } else if (dir == 2 && y <= left) {
                bottom--;
                dir = (dir + 1) % 4;
            } else if (dir == 3 && x <= top) {
                left++;
                dir = (dir + 1) % 4;
            }
            x += dirs[dir][0];
            y += dirs[dir][1];
        }
        return result;
    }
}
gzdaijie            updated 2016-05-25 20:29:07

results matching ""

    No results matching ""